package com.axend.aerosense.room.ui.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.fragment.MvvmBaseFragment;
import com.axend.aerosense.base.impl.IComplete;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.common.bean.UserIconBean;
import com.axend.aerosense.common.bean.UserInfo;
import com.axend.aerosense.common.util.HeadIconUploadService;
import com.axend.aerosense.common.util.UserImageEngine;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.axend.aerosense.room.entity.PersonInfoBean;
import com.axend.aerosense.room.entity.PhoneAreaCodeBean;
import com.axend.aerosense.room.ui.activity.PeoplePickerActivity;
import com.axend.aerosense.room.ui.activity.PhoneCodePieckerActivity;
import com.axend.aerosense.room.ui.activity.RoomAddActivity;
import com.axend.aerosense.room.viewmodel.PersonInfoViewModel;
import com.blankj.utilcode.util.ToastUtils;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.impl.IOperationDetailResult;
import com.axend.aerosense.base.impl.IOperationResult;
import com.axend.aerosense.base.livedatabus.LiveDatabus;
import com.axend.aerosense.base.viewmodel.BaseViewModelFactroy;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.ui.CustomTipsDialog;
import com.axend.aerosense.room.BR;
import com.axend.aerosense.room.R;
import com.axend.aerosense.room.databinding.RoomFragmentNewPsersonBinding;
import com.blankj.utilcode.util.Utils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;

import java.io.File;
import java.util.List;

/**
 * 监护人,紧急联系人新增界面
 */
public class RoomPersonSettingFragment extends MvvmBaseFragment<RoomFragmentNewPsersonBinding, PersonInfoViewModel>
        implements ILoadDataResult<PersonInfoBean>, IComplete {
    private CustomTipsDialog dialog;
    public final static String OPEN_UID = "OPEN_UID";
    private String uid = null;
    // 是否是创建模式
    private boolean CREATE_OPEN_MODE = false;
    private Bitmap upBitmap;

    @Override
    protected void initParameters() {
        super.initParameters();
        Bundle bundle = getArguments();
        if(null != bundle){
            uid = bundle.getString(OPEN_UID);
        }

        if(TextUtils.isEmpty(uid)){
            CREATE_OPEN_MODE = true;
        }else{
            CREATE_OPEN_MODE = false;
        }

    }

    public static RoomPersonSettingFragment getInstance(String uid){
        RoomPersonSettingFragment fragment = new RoomPersonSettingFragment();
        if(!TextUtils.isEmpty(uid)){
            Bundle bundle = new Bundle();
            bundle.putString(OPEN_UID, uid);
            fragment.setArguments(bundle);   //设置参数
        }

        return fragment;
    }

    @Override
    public int getLayoutId() {
        return R.layout.room_fragment_new_pserson;
    }

    @Override
    public int getBindingVariable() {
        return BR.data;
    }

    @Override
    protected PersonInfoViewModel getViewModel() {
        BaseViewModelFactroy<PersonInfoBean> factroy = new BaseViewModelFactroy<PersonInfoBean>(this, this);
        PersonInfoViewModel tmp = new ViewModelProvider(this, factroy).get(PersonInfoViewModel.class);
        if(CREATE_OPEN_MODE){
            // 创建模式, 默认可编辑
            tmp.edit.setValue(true);
            tmp.editHeadImage.setValue(false);
        }else{
            // 已有模式打开,默认不能编辑
            tmp.edit.setValue(false);
            tmp.editHeadImage.setValue(true);
        }
        return tmp;
    }

    @Override
    protected void onRetryBtnClick() {

    }

    @Override
    public void onResume() {
        super.onResume();
        ((PeoplePickerActivity)getActivity()).setRightTitleClickable(true);
        if(CREATE_OPEN_MODE){
            ((PeoplePickerActivity)getActivity()).setTitle(getString(R.string.room_add_pserson));
            ((PeoplePickerActivity)getActivity()).setRightTitle(getString(R.string.common_complete));

        }else{
            if(viewModel.edit.getValue()){
//                ((PeoplePickerActivity)getActivity()).setTitle(getString(R.string.common_person_detail));
                ((PeoplePickerActivity)getActivity()).setRightTitle(getString(R.string.common_save));
            }else{
                ((PeoplePickerActivity)getActivity()).setRightTitle(getString(R.string.common_edit));
            }
            ((PeoplePickerActivity)getActivity()).setTitle(TextUtils.isEmpty(viewModel.personInfo.getValue().getEmergencyName())? getString(R.string.common_person_detail):viewModel.personInfo.getValue().getEmergencyName());
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }

    private void init(){
        if(!CREATE_OPEN_MODE){
            setLoadSir(viewDataBinding.roomContentView);
            showLoading();
            viewModel.getPerson(uid);

        }

        viewDataBinding.roomPhoneCode.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), PhoneCodePieckerActivity.class);
            getActivity().startActivityForResult(intent, PhoneCodePieckerActivity.PERSON_REQUEST_CODE);
        });

        if(!CREATE_OPEN_MODE){
            viewDataBinding.roomDelete.setVisibility(View.VISIBLE);

            viewDataBinding.roomDelete.setOnClickListener(v->{
                if(!TextUtils.isEmpty(uid)){
                    dialog = new CustomTipsDialog(getActivity(), getString(R.string.common_delete_person));
                    dialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener(){

                        @Override
                        public void onPositiveClick() {
                            viewModel.deletePerson(getActivity(), uid, new IOperationDetailResult() {
                                @Override
                                public void onSuccess(Object o) {
                                    dialog.dismiss();
                                    ToastUtils.showShort(R.string.common_success);
                                    getActivity().setResult(RoomAddActivity.RESPONSE_CODE_CLOSE);
                                    LiveDatabus.getInstance().with(Gobal.EVENT_KEY.PERSON_COUNT_CHANGE ,Integer.class).postValue(1);
                                    getActivity().finish();
                                }

                                @Override
                                public void onFail(int errCode, String message) {
                                    dialog.dismiss();
                                    dialog = null;
                                    if(Gobal.ERROR_CODE.ERR_LOGIN == errCode){
                                        ToastUtils.showShort(R.string.common_login_first);
                                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();

                                    }else if(errCode == Gobal.ERROR_CODE.ERR_DELETE){

//                                        dialog = new CustomTipsDialog(getActivity(), getString(R.string.common_delete_person_tips));
//                                        dialog.setOnClickBottomListener(new CustomTipsDialog.OnClickBottomListener(){
//
//                                            @Override
//                                            public void onPositiveClick() {
//                                                dialog.dismiss();
//                                            }
//
//                                            @Override
//                                            public void onNegtiveClick() {
//                                                dialog.dismiss();
//                                            }
//                                        });
//                                        dialog.show();
                                    }else{
                                        ToastUtils.showShort(message);
                                    }
                                }
                            });
                        }

                        @Override
                        public void onNegtiveClick() {
                            dialog.dismiss();
                        }
                    });
                    dialog.show();

                }
            });
        }else {
            viewDataBinding.roomDelete.setVisibility(View.GONE);
        }

        viewDataBinding.roomUserHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View inflate = LayoutInflater.from(getContext()).inflate(R.layout.common_head_popup_window, null);
                TextView tvPhoto = inflate.findViewById(R.id.common_tv_photo);  //调用照相机
                TextView tvAlbum = inflate.findViewById(R.id.common_tv_album);  //调用相册
                TextView tvCancel = inflate.findViewById(R.id.common_tv_cancel);

                final PopupWindow popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
                popupWindow.setOutsideTouchable(true);//设置外部可触摸
                popupWindow.setFocusable(true);//这里必须设置为true才能点击区域外或者消失
                popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                //得到父layout
                View parent = LayoutInflater.from(getActivity()).inflate(getLayoutId(), null);
                //展示在parent的下方，0,0的位置
                popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);

                //popupWindow在弹窗的时候背景半透明
                final WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();

                params.alpha = 0.5f;
                getActivity().getWindow().setAttributes(params);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        params.alpha = 1.0f;
                        getActivity().getWindow().setAttributes(params);
                    }
                });
                //拍照选择
                tvPhoto.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        loadPicture(RoomPersonSettingFragment.this);
                        popupWindow.dismiss();
                    }
                });
                //从相册中选择
                tvAlbum.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        loadPicture(RoomPersonSettingFragment.this);
                        popupWindow.dismiss();
                    }
                });
                //关闭弹出
                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                    }
                });

            }
        });
    }


    @Override
    public void complete() {
        long currentTime = System.currentTimeMillis();
        if(currentTime - clickTime < 2*1000){
            return;
        }
        clickTime = currentTime;
        // 工具栏按钮事件
        if(!CREATE_OPEN_MODE){
            if(viewModel.edit.getValue()){
                // 检查数据是否有更新,有更新数据
                viewModel.updatePerson(getActivity(), new IOperationResult() {
                    @Override
                    public void onSuccess() {
                        // 可编辑模式下,可编辑状态点击工具栏,应当关闭编辑,提示变为编辑
                        if(upBitmap == null){
                            ((PeoplePickerActivity)getActivity()).setRightTitle(getActivity().getString(R.string.common_edit));
                            viewModel.edit.setValue(false);
                            LiveDatabus.getInstance().with(Gobal.EVENT_KEY.PERSON_COUNT_CHANGE ,Integer.class).postValue(1);
                            getActivity().onBackPressed();
                            return;
                        }

                        HeadIconUploadService.upload(upBitmap, 1, uid, new SimpleCallBack<UserIconBean>() {
                            @Override
                            public void onError(ApiException e) {
                                e.printStackTrace();
                                ToastUtils.showShort(e.getMessage());
                                ((PeoplePickerActivity)getActivity()).setRightTitle(getActivity().getString(R.string.common_save));
                                viewModel.edit.setValue(true);
                            }

                            @Override
                            public void onSuccess(UserIconBean bean) {
                                // 可编辑模式下,可编辑状态点击工具栏,应当关闭编辑,提示变为编辑
                                ((PeoplePickerActivity)getActivity()).setRightTitle(getActivity().getString(R.string.common_edit));
                                viewModel.edit.setValue(false);
                                LiveDatabus.getInstance().with(Gobal.EVENT_KEY.PERSON_COUNT_CHANGE ,Integer.class).postValue(1);
                                upBitmap = null;
                                getActivity().onBackPressed();

                            }

                            @Override
                            public void onTokenExpire() {
                                upBitmap = null;
                                ToastUtils.showShort(R.string.common_login_first);
                                ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                            }
                        });
                    }

                    @Override
                    public void onFail() {
                        // 可编辑模式下,不可编辑状态点击工具栏,应当打开编辑,提示变为保存
                        ((PeoplePickerActivity)getActivity()).setRightTitle(getActivity().getString(R.string.common_save));
                        viewModel.edit.setValue(true);
                    }
                });
            }else{
                // 可编辑模式下,不可编辑状态点击工具栏,应当打开编辑,提示变为保存
                ((PeoplePickerActivity)getActivity()).setRightTitle(getActivity().getString(R.string.common_save));
                viewModel.edit.setValue(true);
//                ((PeoplePickerActivity)getActivity()).setTitle(getString(R.string.common_person_detail));
            }
        }else{
            // 此处提交创建数据
            viewModel.addPerson(getActivity(), upBitmap, new IOperationDetailResult<PersonInfoBean>() {
                @Override
                public void onSuccess(PersonInfoBean bean) {
                    if(upBitmap == null){
                        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.PERSON_COUNT_CHANGE ,Integer.class).postValue(1);
                        getActivity().onBackPressed();

                    }else {
                        upBitmap = null;
                        ToastUtils.showShort(Utils.getApp().getString(R.string.common_success));
                        LiveDatabus.getInstance().with(Gobal.EVENT_KEY.PERSON_COUNT_CHANGE ,Integer.class).postValue(1);
                        getActivity().onBackPressed();
                    }
                }

                @Override
                public void onFail(int code, String msg) {

                }
            });
        }
    }

    @Override
    public void loadDataSuccess(PersonInfoBean personInfoBean) {
        viewModel.setValue(personInfoBean);
        Glide.with(getActivity()).load(personInfoBean.getEmergencyImg()).placeholder(R.mipmap.common_img_default_head)
                .skipMemoryCache(true)
                .diskCacheStrategy( DiskCacheStrategy.NONE ).circleCrop().into(viewDataBinding.roomUserHead);
        if(!CREATE_OPEN_MODE){
            // 展示联系人信息
            ((PeoplePickerActivity)getActivity()).setTitle(personInfoBean.getEmergencyName());
        }
    }

    @Override
    public void loadDataFail(String decs) {
        ToastUtils.showShort(decs);
    }

    public void setPhoneCode(PhoneAreaCodeBean bean){
        if(null == bean){
            return;
        }
        PersonInfoBean personInfoBean = viewModel.personInfo.getValue();
        personInfoBean.setEmergencyPhoneAreaCode(bean.getAreaCodePhone());
        viewModel.personInfo.postValue(personInfoBean);
    }

    private void loadPicture(Fragment fragment){
        PictureSelector.create(fragment)
                .openGallery(PictureMimeType.ofImage())  //打开相册
                .imageEngine(UserImageEngine.createGlideEngine())
                .selectionMode(PictureConfig.SINGLE) //单选模式
                .isEnableCrop(true) //可以裁剪
//                                .circleDimmedLayer(true) //圆形裁剪框
//                                .setCircleStrokeWidth(3) //圆形裁剪框宽度
                .showCropFrame(true) //不显示矩形裁剪框
                .hideBottomControls(true) //隐藏裁剪工具栏
                .isCompress(true) //压缩图片
                .minimumCompressSize(10) //大于100kb都要压缩
                .withAspectRatio(1, 1)//裁剪比例
                .cropImageWideHigh(170, 170)//裁剪宽高
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        LocalMedia localMedia = result.get(0);
                        String path = "";
                        if (localMedia.isCut()) {//是否裁剪
                            path = localMedia.getCutPath();
                        } else {
                            path = localMedia.getRealPath();
                        }
                        Glide.with(fragment).asBitmap().load(path).into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                upBitmap = resource;
                                Glide.with(fragment).load(resource).circleCrop().into(viewDataBinding.roomUserHead);
                            }
                        });
                    }

                    @Override
                    public void onCancel() {
                    }
                });
    }

}
